// ==UserScript==
// @name         北方工业大学学生工具箱
// @namespace    https://www.bailemen.jp.eu.org/
// @version      0.5.2
// @description  为北方工业大学学生那些令人无语的日常繁琐事务提供一些便捷解决方案，欢迎反馈和建议！
// @author       Bluemagpie
// @match        10-32-31-36-6188.webvpn.ncut.edu.cn/smarttt/*
// @match        10.32.31.36:8188/smarttt/*
// @match        https://*.ncut.edu.cn/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=ncut.edu.cn
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function () {
    'use strict';

    // 用户自定义参数，只允许用户交互这部分
    const USER_CONFIG = {
        DEFAULT_SCORE: 10,
        FORCE_UA: true
    }

    // 通用功能函数
    const utils = {
        // Cookie操作
        cookie: {
            get(name) {
                const cookies = document.cookie.split(';');
                for (let cookie of cookies) {
                    const [key, value] = cookie.split('=');
                    if (key.trim() === name) {
                        return JSON.parse(decodeURIComponent(value.trim()));
                    }
                }
                return null;
            },

            set(name, value, days) {
                const date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = `${name}=${encodeURIComponent(JSON.stringify(value))}; expires=${date.toUTCString()}; path=/`;
            }
        },
    }

    // 运行核心参数
    const ADMIN_CONFIG = {
        TIME_OVER: 1000,
        COMMENT_EXPIRES_DAYS: 30,
        MAIN_FORM: 'form[name="notice"]',
        SELECT_LIST: 'select[name="kcxuanze"]',
        RADIO_SELECTOR: 'input[type="radio"]',
        FORM_SUBMIT_BTN: 'input[type="submit"][id="submit01"]',
        SELECT_SUBMIT_BTN: 'input'
    };

    function modifyUA() {
        try {
            const originalUA = navigator.userAgent;
            if (!originalUA) return false; // 异常情况保护

            const isChrome = originalUA.includes('Chrome');
            if (!isChrome) {
                const targetUA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0';
                Object.defineProperty(navigator, 'userAgent', {
                    value: targetUA,
                    writable: false,
                    configurable: false,
                    enumerable: true
                });
            }

            return true;
        }
        catch (e) {
            console.error('[UA 错误] 修改失败:', e);
            return false;
        }
    }

    function checkInitialForm(targetScore) {
        const form = document.querySelector(ADMIN_CONFIG.MAIN_FORM);
        if (!form) return false;

        // 检查radio是否全部选中
        const radios = form.querySelectorAll(
            `${ADMIN_CONFIG.RADIO_SELECTOR}[id="${targetScore}"]`
        );
        if (!radios.length) return false;

        const hasUnchecked = [...radios].some(radio => !radio.checked);
        if (hasUnchecked) {
            // 选中所有目标radio
            radios.forEach(radio => {
                radio.checked = true;
            });

            // 提交表单
            form?.submit();

            return true;
        }

        return true;
    }

    function processCurrentOption() {
        const selectList = document.querySelector(ADMIN_CONFIG.SELECT_LIST);
        if (!selectList) return false;

        const resetIndex = 1;
        const targetOption = selectList.options[resetIndex];
        if (targetOption && /\[已评\]/.test(targetOption.textContent)) {
            return true;
        } else {
            if (selectList.selectedIndex !== resetIndex) selectList.selectedIndex = resetIndex;
        }

        // 提交select变更
        const submitBtn = document.querySelector(ADMIN_CONFIG.SELECT_SUBMIT_BTN);
        submitBtn?.click();

        return false;
    }

    // 评教表单填写逻辑
    function autoEvaluation(targetScore, attemptMax = 5, attemptCount = 0) {
        try {
            const successForm = checkInitialForm(targetScore);
            const successSelect = processCurrentOption();

            if (successSelect) {
                console.log('评教完成！');

                return
            } else if (successForm) throw new Error('等待翻页中...');
            else throw new Error('等待评教表单加载中...');
        } catch (error) {
            if (attemptCount < attemptMax) {
                // console.log('评教未进行，', error);
                setTimeout(() => {
                    const attemptNext = attemptCount + 1
                    // console.log(`第${attemptNext}次重试...`);
                    autoEvaluation(targetScore, attemptMax, attemptNext);
                }, ADMIN_CONFIG.TIME_OVER);
            } else {
                console.error('评教失败，超过最大重试次数！');

                return;
            }
        }
    }

    // 主逻辑
    const host = window.location.hostname;

    // 教学平台UA修复
    if ((host.includes('10-32-31-36') || host.includes('10.32.31.36')) && USER_CONFIG.FORCE_UA) {
        if (!modifyUA()) {
            alert('UA修改失败，请手动刷新页面后重试！错误信息请查看控制台');
        }
    }

    if (/^jxxx-443\.webvpn\.ncut\.edu\.cn$/i.test(host)) {
        autoEvaluation(USER_CONFIG.DEFAULT_SCORE);
    }
})();